package org.mbds.android.p2p.threads;


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.util.ArrayList;

import org.mbds.android.p2p.services.P2pService;

import android.os.AsyncTask;

public class Getter extends AsyncTask<Socket, String, String>{
	P2pService mService;
	Socket mClient;
	
	public Getter(P2pService service){
		mService = service;
	}
	@Override
	protected String doInBackground(Socket... params) {
		mClient = params[0];
		BufferedReader br = null;
		String result = "";
		try {
			br = new BufferedReader(new InputStreamReader(mClient.getInputStream()));
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		while(mClient != null && mClient.isConnected() && !mClient.isInputShutdown() && !mClient.isOutputShutdown()){
			try {
				if(br.ready()){
					while(br.read() != -1){
						result += br.readLine();
					}
					break;
				}
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
		try {
			if(br != null)
				br.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return result;
	}
	
	
	@Override
	protected void onPostExecute(String result){
		mService.returnMessage(result);
	}
}
